package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.RedisConst;
import com.itheima.dao.OrderDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetmealImpl implements SetmealService {

    @Autowired
    SetmealDao setmealDao;

    @Autowired
    JedisPool jedisPool;

    @Autowired
    OrderDao orderDao;


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page);
    }

    @Override
    public void add(Setmeal setmeal, Integer[] ids) {
        setmealDao.add(setmeal);
        if (setmeal.getId() != null) {
            xunhuan(setmeal.getId(), ids);
        }
        Jedis resource = jedisPool.getResource();
        resource.srem(RedisConst.SETMEAL_PIC_RESOURCES, setmeal.getImg());
    }

    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> setmeals = setmealDao.findAll();
        return setmeals;
    }

    @Override
    public Setmeal findCheckGroupsAndCheckItemsBySetmealId(Integer id) {

        Setmeal setmeal = setmealDao.findCheckGroupsAndCheckItemsBySetmealId(id);

        return setmeal;
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        return setmeal;
    }


    // 添加检查组和检查项的中间表
    public void xunhuan(Integer id, Integer[] ids) {
        for (Integer ids1 : ids) {
            setmealDao.insertData(id, ids1);
        }
    }

    public Map<String, Object> getSetmealReport() {

        List<Setmeal> all = setmealDao.findAll();

        HashMap<String, Object> maps = new HashMap<>();

        ArrayList<String> list = new ArrayList<>();

        List<Map<String, Object>> list2 = new ArrayList<>();

        for (Setmeal setmeal : all) {
            String setmealName = setmeal.getName();
            list.add(setmealName);
            Integer count = orderDao.findBySetmealId(setmeal.getId());
            HashMap<String, Object> map = new HashMap<>();
            map.put("value", count);
            map.put("name", setmealName);
            list2.add(map);
        }
        maps.put("setmealNames", list);
        maps.put("setmealCount", list2);

        return maps;
    }


}
